package edu.lnu.project.timeeditapp.activites;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.lnu.project.timeeditapp.R;
import edu.lnu.project.timeeditapp.db.TimeEditDataSource;
import edu.lnu.project.timeeditapp.parser.Event;
import edu.lnu.project.timeeditapp.parser.ImportFiles;
import edu.lnu.project.timeeditapp.parser.XlsParser;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class SelectFileActivity extends ListActivity {


	private List<File> files = new ArrayList<File>();
	private ArrayAdapter<File> myAdapter;
	private TimeEditDataSource datasource;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		//Set up the action bar
		ActionBar actionBar = getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);
	    
		//Create adapter
		myAdapter = new ArrayAdapter<File>(this, R.layout.xls_file_list_item, files);

		//Set adapter
		setListAdapter(myAdapter);


		//Attach list item listener
		addListListener(this);

		//Initialize the datasource
		datasource = new TimeEditDataSource(this);

		//Scan the SD-Card when this activity starts
		scanSDCard();

	}

	@Override
	protected void onPause() {
		finish(); 
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		files.clear();
		myAdapter.clear();
		myAdapter.notifyDataSetChanged();

		super.onDestroy();
	}

	/**
	 * Sets up the listview listener and contains onclickitem
	 */
	private void addListListener(final Activity activity){
		getListView().setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				File sourceFile = files.get(position);
				boolean succes = addEventsFromFileToDB(sourceFile);			

				if( succes ){
					StartActivity.initializePrefEditor.putBoolean(StartActivity.INITIALIZED, true).commit();
					/* Close this activity*/
					finish();
				}
			}}); 
	}

	/**
	 * 
	 * @param File that will be parsed
	 * @return true if the parsing was successful false otherwise
	 */
	private boolean addEventsFromFileToDB(File sourceFile) {
		try{
			datasource.open();

			//Get all events from the file
			ArrayList<Event> events = XlsParser.parseThisFile(sourceFile);

			//Clear the database before we put in new events
			datasource.deleteAllEvents();

			//Add all events in the database
			for(Event event : events){
				datasource.createEvent(event);
			}
			datasource.close();

			//Return true when we where able to parse the file
			return true;
		}
		catch( Exception e){
			System.out.println("Error: "+e);
			Toast.makeText(this, "Unable to parse that file "+e, Toast.LENGTH_LONG).show();

			//Return false when we where not able to pars the file
			return false;
		}
	}

	/**
	 * Prepare and start the AsyncTask that scans the SD-Card
	 */
	private void scanSDCard(){
		//Clear the lists before we fill them with new files
		myAdapter.clear();
		files.clear();

		//Create AsyncTask
		AsyncTask<Void, Void, Void> task = new ScanSDCard();

		//Start AsyncTask
		task.execute();
	}

	/**
	 * 
	 * Add action menu
	 * 
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.action_menu_selectfile, menu);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) { 	
		switch (item.getItemId()) {
		case R.id.refresh_selectfile:
			scanSDCard();
			return true;
		default: 
			finish();
			return false;
		}
	}

	/**
	 * 
	 * @author Libra
	 *
	 * AsyncTask that will show a progress ring dialog while searching throw the files on the sd card
	 *
	 */
	private class ScanSDCard extends AsyncTask<Void, Void, Void>
	{
		private ProgressDialog ringProgressDialog;

		@Override
		protected void onPreExecute() {
			//Create and start Progress Dialog
			ringProgressDialog = ProgressDialog.show(SelectFileActivity.this, "Please wait ...", "Searching for files ...", true);
			ringProgressDialog.setCancelable(true);
			myAdapter.clear();
			files.clear();
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) 
		{
			//Get the specified files
			files = ImportFiles.getFiles();
			return null;
		}

		@Override
		protected void onPostExecute(Void result) 
		{
			super.onPostExecute(result);
			//Remove the Progress Dialog
			ringProgressDialog.dismiss();

			//Show all files in the listView
			if( files != null ){
				for(File file : files ){
					myAdapter.add(file);
				}
			}
			myAdapter.notifyDataSetChanged();
		}

	}

}




